package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.StgyException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.AttrValue;
import com.atguigu.lease.web.admin.mapper.AttrKeyMapper;
import com.atguigu.lease.web.admin.service.AttrKeyService;
import com.atguigu.lease.web.admin.service.AttrValueService;
import com.atguigu.lease.web.admin.vo.AttrKeyVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.lease.model.entity.AttrKey;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author 1
* @description 针对表【attr_key(房间基本属性表)】的数据库操作Service实现
* @createDate 2024-08-28 11:00:25
*/
@Service
public class AttrKeyServiceImpl extends ServiceImpl<AttrKeyMapper, AttrKey>
    implements AttrKeyService {
    @Resource
    AttrValueService attrValueService;
    @Override
    public List<AttrKeyVo> listAttrKeyVos() {
        //先查询 AttrKey的集合  再遍历查询每个AttrKey的 AttrValue子集合
        //自定义sql实现： 两表联查(表数据量不大)  数据量大了联查时需要sql优化-创建索引
        return baseMapper.selectAttrKeyVos();
    }

    @Override
    public boolean saveOrUpdateAttrKey(AttrKey attrKey) {
        long id = attrKey.getId()==null?-1L:attrKey.getId();
        AttrKey dbAttrKey = this.getOne(Wrappers.lambdaQuery(AttrKey.class)
                .eq(AttrKey::getName, attrKey.getName())
                .last("limit 1"));

        if(dbAttrKey!=null && id != dbAttrKey.getId().longValue()){
            throw new StgyException(ResultCodeEnum.DATA_EXISTS_ERROR);
        }
        return this.saveOrUpdate(attrKey);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteById(Long attrKeyId) {
        this.removeById(attrKeyId);
        attrValueService.remove(Wrappers.lambdaQuery(AttrValue.class)
                .eq(AttrValue::getAttrKeyId , attrKeyId));
        return true;
    }
}




